package com.cunfang.base.service;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cunfang.base.dao.DaoSupport;

import com.cunfang.entity.Page;
import com.cunfang.entity.PageData;
import com.cunfang.entity.UserInfo;
import com.cunfang.util.CONNECTOR;
import com.cunfang.util.DateJsonValueProcessor;
import com.cunfang.util.UuidUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;



/**
 * @功能：初始 Service
 * @作者：RC
 * */
public class BaseService {
	
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Resource(name = "daoSupport")
	private DaoSupport dao;
	

	public DaoSupport getDao() {
		return dao;
	}

	/** 判断是否存在 **/
	public Boolean Exist(String sql) {
		return dao.findExist(sql);
	}

	/** 得到唯一值 **/
	public Object Singe(String sql) {
		return dao.findSinge(sql);
	}

	/** 执行批量sql **/
	public Integer ExecuteSql(List<String> listsql) {
		return dao.ExecuteSql(listsql);
	}

	/** 单个执行sql **/
	public Integer ExecuteSql(String sql) {
		return dao.ExecuteSql(sql);
	}

	/** 根据sql得到list **/
	public List<PageData> Query(String sql) {
		return dao.Query(sql);
	}



	/** 常用工具 *******/

	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();

		return request;
	}

	/**
	 * 得到当前的token
	 * */
	public String GetToken() {
		/* 第一： token存放在header中 */
		String token = this.getRequest().getHeader("token");
		if (token == null) {
			/* 第二：token存放在url参数中 */
			token = this.getRequest().getParameter("token");
		}
		return token;
	}

	/**
	 * 得到当前的token
	 * */
	public String GetTokenID() {
		String token = this.GetToken();
		return CONNECTOR.GetTokenValue(token);
	}

	/**
	 * 
	 * @功能: 得到当前登录人的session
	 * @作者: ZhuHongKai
	 * @日期: 2017年1月13日
	 */
	public UserInfo getUserInfo() {
		UserInfo user = null;
		HttpSession session = this.getRequest().getSession();
		if (session != null) {
			user = (UserInfo) session.getAttribute(UserInfo.SESSION_USER);
		}
		return user;
	}

	
	/**
	 * 
	 * @功能: 设置登录人信息
	 */
	public void setUserInfo(UserInfo user) {
		this.getRequest().getSession().setAttribute(UserInfo.SESSION_USER, user);
	}
	/**
	 * 
	 * @功能: 获取用户权限列表信息
	 * @作者: rxj
	 */
	public List<String> getPermission(List<String> permission) {
		List<String> permissiionList = null;
		HttpSession session = this.getRequest().getSession();
		if (session != null) {
			permissiionList = (List<String>) session.getAttribute(UserInfo.USER_PERMISSION);
		}
		return permissiionList;
	}
	/**
	 * 
	 * @功能: 设置用户权限列表信息
	 * @作者: rxj
	 */
	public void setPermission(List<String> permission) {
		this.getRequest().getSession().setAttribute(UserInfo.USER_PERMISSION, permission);
	}

	
	/**
	 * 
	 * @功能: 存储session
	 */
	public void setSession(String key, Object name) {
		this.getRequest().getSession().setAttribute(key, name);
	}

	/**
	 * 
	 * @功能: 获取key的session
	 */
	public Object getSession(String key) {
		HttpSession session = this.getRequest().getSession();
		if (session != null) {
			return session.getAttribute(key);
		}
		return null;
	}

	/**
	 * 得到36位的uuid
	 * 
	 */
	public String getUUID() {
		return UuidUtil.getUUID().toUpperCase();
	}

	/**
	 * 
	 * @功能: 得到格式化后的时间，默认格式（yyyy-MM-dd HH:mm:ss）
	 */
	public String getDateTime(String format) {
		String type = "yyyy-MM-dd HH:mm:ss";
		Date nowDate = new Date();
		if (format != null && format.length() > 0) {
			type = format;
		}
		SimpleDateFormat formatDate = new SimpleDateFormat(type);
		return formatDate.format(nowDate);
	}

	/**
	 * @功能：打印List
	 * */
	public String outObject(Object obj) {
		String str = "";
		if (obj != null) {
			JsonConfig config = new JsonConfig();
			config.registerJsonValueProcessor(Timestamp.class,
					new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
			if (obj instanceof PageData || obj instanceof Map) {
				str = JSONObject.fromObject(obj, config).toString();
			} else {
				str = JSONArray.fromObject(obj, config).toString();
			}
		} else {
			str = "{}";
		}
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		return str;
	}

	/**
	 * @功能：打印PageData
	 * @参数：pd需要转换的PageData,dateFormat时间格式化的PageData,bl是否需要status字符串,bl1是否进行格式化json
	 * */
	@SuppressWarnings("rawtypes")
	public String outPageData(PageData pd, PageData dateFormat, Boolean bl,
			Boolean bl1) {
		String str = "";
		Map.Entry me;
		str = "{";
		if (pd != null) {
			Iterator it = pd.entrySet().iterator();
			String value = "";
			while (it.hasNext()) {
				me = (Map.Entry) it.next();
				value = me.getValue() + "";
				if (bl1) {
					value = this.scanString(me.getValue(), me.getKey(),
							dateFormat);
				}
				str += "\"" + me.getKey() + "\":\"" + value + "\",";
			}
		}
		if (str.length() > 1) {
			str = str.substring(0, str.length() - 1); /* 去除逗号 */
		}
		str += "}";
		if (bl) {
			str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		}
		return str;
	}

	public String outPageData(PageData pd) {
		return outPageData(pd, new PageData(), true, true);
	}

	public String outPageData(PageData pd, Boolean bl) {
		return outPageData(pd, new PageData(), bl, true);
	}

	public String outPageData(PageData pd, String dateFormat) {
		PageData date = new PageData();
		date.put("ALL", dateFormat);
		return outPageData(pd, date, true, true);
	}

	/**
	 * @功能：打印List PageData
	 * */
	@SuppressWarnings("rawtypes")
	public String outListPageData(List<PageData> list, PageData dateFormat) {
		String str = "";
		Map hs;
		Iterator it;
		Map.Entry me;
		/* 拼接 json */
		str += "[";
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i) == null)
					continue;

				hs = list.get(i).map;
				str += "{";
				it = hs.entrySet().iterator();
				while (it.hasNext()) {
					me = (Map.Entry) it.next();
					str += "\""
							+ me.getKey()
							+ "\":\""
							+ this.scanString(me.getValue(), me.getKey(),
									dateFormat) + "\",";
				}
				str = str.substring(0, str.length() - 1); /* 去除逗号 */
				str += "},";
			}
			if (list.size() > 0) {/* 去除逗号 */
				str = str.substring(0, str.length() - 1);
			}
		}
		str += "]";
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		return str;
	}

	public String outListPageData(List<PageData> list) {
		return outListPageData(list, new PageData());
	}

	public String outListPageData(List<PageData> list, String dateFormat) {
		PageData date = new PageData();
		date.put("ALL", dateFormat);
		return outListPageData(list, date);
	}

	/**
	 * @功能：打印Page
	 * @作者：RC
	 * @日期：2016-11-04
	 * */
	@SuppressWarnings("rawtypes")
	public String outPage(Page page, List<PageData> list, PageData dateFormat) {
		String str = "";
		Map hs;
		Iterator it;
		Map.Entry me;
		/* 拼接 json */
		str += "[";
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i) == null)
					continue;

				hs = list.get(i).map;
				str += "{";
				it = hs.entrySet().iterator();
				while (it.hasNext()) {
					me = (Map.Entry) it.next();
					str += "\""
							+ me.getKey()
							+ "\":\""
							+ this.scanString(me.getValue(), me.getKey(),
									dateFormat) + "\",";
				}
				str = str.substring(0, str.length() - 1); /* 去除逗号 */
				str += "},";
			}
			if (list.size() > 0) {/* 去除逗号 */
				str = str.substring(0, str.length() - 1);
			}
		}
		str += "]";

		/* 拼接分页... */
		str = "{\"totalpage\":" + page.getTotalPage() + ",\"currpage\":"
				+ page.getCurrentPage() + ",\"count\":" + page.getShowCount()
				+ ",\"totalresult\":\"" + page.getTotalResult()
				+ "\",\"data\":" + str + "}";
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		return str;
	}

	public String outPage(Page page, List<PageData> list) {
		return outPage(page, list, new PageData());
	}

	public String outPage(Page page, List<PageData> list, String dateFormat) {
		PageData date = new PageData();
		date.put("ALL", dateFormat);
		return outPage(page, list, date);
	}

	/**
	 * @功能：打印正确信息
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	public String outString(String str) {
		str = "{\"status\":\"0\",\"msg\":\"" + this.scanString(str) + "\"}";
		return str;
	}

	/**
	 * @功能：打印错误记录
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	public String outError(String str) {
		str = "{\"status\":\"1\",\"msg\":\"" + this.scanString(str) + "\"}";
		return str;
	}

	/**
	 * @功能：打印错误记录
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	public String outError(String errMsg, Object obj) {
		String str = "";
		if (obj != null) {
			if (obj instanceof PageData) {
				str = JSONObject.fromObject(obj).toString();
			} else {
				str = JSONArray.fromObject(obj).toString();
			}
		} else {
			str = "{}";
		}
		str = "{\"status\":\"1\",\"msg\":\"" + errMsg + "\",\"data\":" + str
				+ "}";
		return str;
	}

	/**
	 * JSon 数据中的String 传递数据时，需要处理好特殊字符 JSon数据中有特殊字符 1:引号 如果是使用单引号，来括值的话，那String
	 * 中 ' 单引号为特殊字符 2：正斜杠，反斜杠，换行符号等 3:另外，必须用 (") 而非 (') 表示字符串：
	 * 
	 * @param str
	 * @return String类型
	 * @createTime 2014-9-4
	 * @author Sunqinbo
	 */
	public String scanString(Object obj, Object key, PageData pd) {
		if (obj == null) {
			return "";
		}
		/* 转换时间类型 */
		if (obj instanceof java.util.Date && pd != null) {
			SimpleDateFormat formatter = null;
			if (pd.containsKey(key)) {
				formatter = new SimpleDateFormat(pd.getString(key));
			} else {
				formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			}
			return formatter.format(obj);
		}
		String s = obj.toString();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public String scanString(Object obj) {
		return scanString(obj, "", null);
	}

}
